# 设置DuckDNS token和域名
$duckToken = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
$duckDomain = "myhome"

# 使用Resolve-DnsName获取DuckDNS记录中的IPv6地址
function Get-DuckDNSIPv6 {
    param(
        [string]$Domain
    )

    try {
        $dnsRecord = Resolve-DnsName -Name $Domain -Type AAAA
        if ($dnsRecord.IPAddress) {
            "DuckDNS记录中的IPv6地址为: $($dnsRecord.IPAddress)" | Out-File -FilePath "D:\App\DuckDNS\log.txt" -Append
            return $dnsRecord.IPAddress
        }
    }
    catch {
        "无法解析DuckDNS域名 $Domain 的IPv6地址。错误信息：$($_.Exception.Message)" | Out-File -FilePath "D:\App\DuckDNS\log.txt" -Append
    }
    return $null
}
# 定义一个函数来获取IPv6地址
function Get-IPv6FromServices {
    param(
        [string[]]$Urls
    )

    foreach ($url in $Urls) {
        try {
            $currentIP = (Invoke-WebRequest -Uri $url).Content.Trim()
            if ($currentIP -match "^[A-Fa-f0-9:]+$") {
                "获取到IPv6: $currentIP" | Out-File -FilePath "D:\App\DuckDNS\log.txt" -Append
                return $currentIP
            } else {
                "Error：$currentIP" | Out-File -FilePath "D:\App\DuckDNS\log.txt" -Append
            }
        }
        catch {
            "无法从 $url 获取IPv6地址。错误信息：$($_.Exception.Message)" | Out-File -FilePath "D:\App\DuckDNS\log.txt" -Append
        }
    }
    return $null
}

# 尝试从多个服务获取IPv6地址
$ipv6Urls = @(
    "https://ipv6.ident.me",
    "https://ipv6.wtfismyip.com/text",
    "https://ipv6.seeip.org",
    "https://icanhazip.com",
    "https://checkip.spdyn.de",
    "https://api6.ipify.org"
)
# 获取当前DuckDNS记录中的IPv6地址
$currentDuckDNSIPv6 = Get-DuckDNSIPv6 -Domain "$duckDomain.duckdns.org"
$currentIPv6 = Get-IPv6FromServices -Urls $ipv6Urls

if ($currentIPv6) {
    if ($currentDuckDNSIPv6 -ne $currentIPv6) {
        # 构造更新DuckDNS的URL
        $updateUrl = "https://www.duckdns.org/update?domains=$duckDomain&token=$duckToken&ipv6=$currentIPv6"

        # 发送HTTP GET请求更新DuckDNS
        try {
            $response = Invoke-WebRequest -Uri $updateUrl
            # 输出响应内容
            "更新DuckDNS域名 $duckDomain 成功。响应内容：$response" | Out-File -FilePath "D:\App\DuckDNS\log.txt" -Append
        }
        catch {
            "更新DuckDNS失败。错误信息：$($_.Exception.Message)" | Out-File -FilePath "D:\App\DuckDNS\log.txt" -Append
        }
    } else {
        "当前IPv6地址与DuckDNS记录中的IPv6地址相同，无需更新。" | Out-File -FilePath "D:\App\DuckDNS\log.txt" -Append
    }

} else {
    "无法从任何提供的服务获取有效的IPv6地址." | Out-File -FilePath "D:\App\DuckDNS\log.txt" -Append
}
